package com.examle.agent;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

public class ClassFileTransformerDemo implements ClassFileTransformer {

	public static final String injectedClassName = "com.example.example.Dog2";
	public static final String methodName = "hello";

	public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
			ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
		className = className.replace("/", ".");
		if (className.equalsIgnoreCase(injectedClassName)) {
			CtClass ctclass = null;
			try {
				System.out.println(className);
				ClassPool pool = ClassPool.getDefault();
				ctclass = pool.get(className);// 使用全称,用于取得字节码类<使用javassist>
				CtMethod ctmethod = ctclass.getDeclaredMethod(methodName);// 得到这方法实例
				ctmethod.insertAfter("System.out.println(\"after process Dog2 hello\");");
				return ctclass.toBytecode();
			} catch (Exception e) {
				System.out.println(e.getMessage());
				e.printStackTrace();
			}
		}
		return null;
	}

}
